package me.zingon.webmvc.servlet;

import com.alibaba.fastjson.JSON;
import me.zingon.core.context.SummerContext;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DispatcherServlet extends HttpServlet {

    private final String contextConfigLocation="contextConfigLocation";

    SummerHandlerMapping handlerMapping;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doDispatch(req,resp);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        /**
         * 实例化ioc容器
         */
        SummerContext summerContext=new SummerContext(config.getInitParameter(contextConfigLocation));
        /**
         * 初始化handlermapping
         */
        handlerMapping=new SummerHandlerMapping(summerContext);


    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            SummerHandler handler = handlerMapping.getHandler(req);
            Object result = handler.handle(req, resp);
            if(result!=null) {
                resp.setContentType("text/html");
                resp.setCharacterEncoding("UTF-8");
                resp.getWriter().write(JSON.toJSONString(result));
                resp.getWriter().close();
            }
        }catch (Exception e){
            e.printStackTrace();
            resp.setContentType("text/html");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write("{server:500}");
            resp.getWriter().close();
        }
    }

}
